<template>
  <div id="information-box">
    <div class="run-box">
      <div class="state-box">
        <div class="run-label">消息管理</div>
      </div>
    </div>
    <div class="basic-info">
      <div class="basic-detail">
        <div class="basic-title">消息通知详情</div>
        <div class="basic-btn">
          <button class="btn" @click="dialogVisibtn()" v-if="userType >= 5">新建</button>
          <button class="btn" @click="deleteAs(basicData.data.name)" v-if="userType >= 5">删除</button>
        </div>
      </div>
      <div class="basic-box">
        <div class="content-box" v-for="(item, key) in basic" :key="key">
          <div class="in-box">
            <div class="content-label">{{ item }}</div>
            <div v-if="key !== 'notice_trace_status'" class="content-text">{{ basicData.data[key] }}</div>
            <div v-else class="content - text" v-for="(p, key) in basicData.data.notice_trace_status">
              {{ $t(p) + `&nbsp; ` }}
            </div>
            <div v-if="!basicData.data.notice_trace_status && key !== 'subscription_count'">{{ '--' }}</div>
            <span v-if="key == 'notice_trace_status' && userType >= 5" class="modify" @click="updata()">修改</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 新建 -->
    <el-dialog title="新建消息通知" v-model="dialogVisible" width="30%" center>
      <el-form ref="assRef" :model="information.data.CreateTopic" :rules="rules">
        <el-form-item prop="name">
          <template #label>
            <div class="item-label">主题名称</div>
            <el-tooltip effect="dark" placement="right" content="用于消息通知的主题名称，1-255字符"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-input type="text" v-model="information.data.CreateTopic.name"></el-input>
        </el-form-item>
        <el-form-item prop="enterprise_project_id">
          <template #label>
            <div class="item-label">企业项目ID</div>
            <el-tooltip effect="dark" placement="right" content="企业项目ID, 默认为0(default)"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-input type="text" v-model="information.data.CreateTopic.enterprise_project_id"></el-input>
        </el-form-item>

        <el-form-item prop="notice_trace_status">
          <template #label>
            <div class="item-label">事件级别</div>
            <el-tooltip effect="dark" content="根据事件的级别决定是否短信或邮件通知" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select
            collapse-tags
            collapse-tags-tooltip
            v-model="information.data.CreateTopic.notice_trace_status"
            class="m-2 fleet"
            clearable
            placeholder="请选择事件级别"
            multiple
          >
            <el-option v-for="item in availableOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="createInfo(assRef)">创建</el-button>
          </span>
        </span>
      </template>
    </el-dialog>
    <!-- 修改 -->
    <el-dialog title="修改消息通知" v-model="showRevise" width="30%" center>
      <el-form ref="assRef" :model="subjectDatas">
        <el-form-item prop="notice_trace_status">
          <template #label>
            <div class="item-label">事件级别</div>
            <el-tooltip effect="dark" content="根据事件的级别决定是否短信或邮件通知" placement="bottom"
              ><el-icon><QuestionFilled /></el-icon
            ></el-tooltip>
          </template>
          <el-select v-model="subjectDatas.notice_trace_status" class="m-2 fleet" clearable placeholder="请选择事件级别" multiple>
            <el-option v-for="item in availableOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="updataSubject()">确定</el-button>
          </span>
        </span>
      </template>
    </el-dialog>
    <div class="insert-info">
      <div class="insert-top">
        <div class="insert-title">订阅者列表</div>
        <button class="btn" @click="addSubscription()" v-if="userType >= 5">添加订阅</button>
      </div>
      <div class="insert-table">
        <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#f4f5f8', color: '#252b3a' }" :border="true">
          <el-table-column label="序号" width="130">
            <template #default="scope">
              <div class="id-box">
                {{ scope.$index + 1 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="资源标识">
            <template #default="scope">
              <el-tooltip effect="dark" :content="scope.row.subcription_urn" placement="bottom">
                <div class="idescribe">
                  {{ scope.row.subcription_urn }}
                </div>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="protocol" label="协议">
            <template #default="scope">
              {{ scope.row.protocol ? $t(scope.row.protocol) : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="endpoint" label="联系方式" />
          <el-table-column label="备注">
            <template #default="scope">
              <div class="id-box">
                {{ scope.row.remark }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态">
            <template #default="scope">
              <div class="id-box">
                {{ stateDate[`${scope.row.status}`] }}
              </div>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200" v-if="userType >= 5">
            <template #default="scope">
              <div class="actions-box">
                <div class="actions-delete" @click="unsubscribe(scope.row.subcription_urn)">取消订阅</div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 新建 -->
      <el-dialog title="订阅消息通知" v-model="showAndhide" width="30%" center>
        <el-form ref="assRef" :model="AddSubscription.data" :rules="rules">
          <el-form-item prop="protocol">
            <template #label>
              <div class="item-label">协议</div>
              <el-tooltip effect="dark" content="通知的协议,当前只支持email(邮件)和sms(短信)" placement="bottom"
                ><el-icon><QuestionFilled /></el-icon
              ></el-tooltip>
            </template>
            <el-select collapse-tags collapse-tags-tooltip v-model="AddSubscription.data.protocol" class="m-2 fleet" clearable placeholder="请选择协议">
              <el-option v-for="item in availableOptions1" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="endpoint">
            <template #label>
              <div class="item-label">联系方式</div>
              <el-tooltip effect="dark" placement="right" content="终端节点,协议为email的时候为邮箱地址,为sms的时候为电话号码"
                ><el-icon><QuestionFilled /></el-icon
              ></el-tooltip>
            </template>
            <el-input type="text" v-model="AddSubscription.data.endpoint"></el-input>
          </el-form-item>
          <el-form-item prop="remark">
            <template #label>
              <div class="item-label">备注</div>
              <el-tooltip effect="dark" placement="right" content="订阅者的备注"
                ><el-icon><QuestionFilled /></el-icon
              ></el-tooltip>
            </template>
            <el-input type="text" v-model="AddSubscription.data.remark"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <span class="dialog-footer">
              <el-button @click="showAndhide = false">取消</el-button>
              <el-button type="primary" @click="createSubscription(assRef)">创建</el-button>
            </span>
          </span>
        </template>
      </el-dialog>
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="eventData.offset"
          v-model:page-size="eventData.limit"
          :page-sizes="[10, 20, 50, 100]"
          :small="small"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableTotal"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import appStore from '@/store'
  import { reactive, ref } from 'vue'
  import eventList, { createInformation, information, subscription, theme } from '@/api/eventAudit'
  import { ElMessage, ElMessageBox, FormRules, FormInstance } from 'element-plus'
  import { timeFormathmsUTC } from '@/utils/formatter'
  import state from '@/tips/state.json'
  const stateDate: { [key: string]: string } = reactive(state)
  const basic = {
    name: '消息主题名称',
    display_name: '显示名称',
    topic_urn: '消息主题资源标识',
    enterprise_project_id: '企业项目ID',
    notice_trace_status: '事件级别',
    state_and_reason: '状态以及原因',
    creation_time: '创建时间',
    subscription_count: '订阅者人数'
  }
  const rules = reactive<FormRules>({
    name: [
      {
        required: true,
        message: '请输入用户名',
        trigger: 'blur'
      }
    ],
    protocol: [{ required: true, message: '请选择协议', trigger: 'blur' }],
    endpoint: [{ required: true, message: '请输入联系方式', trigger: 'blur' }]
  })
  let tableData = ref()
  let userType = ref()
  userType.value = localStorage.getItem('UserType') as string
  const createInformation: createInformation = reactive({
    project_id: appStore.userStore.project_id,
    name: '',
    display_name: '',
    enterprise_project_id: '',
    notice_trace_status: ''
  })
  const subjectDatas = reactive({
    project_id: appStore.userStore.project_id,
    notice_trace_status: ''
  })
  const information = reactive({
    data: {
      CreateTopic: createInformation
    }
  })
  const AddSubscription: { data: information } = reactive({
    data: {
      protocol: '',
      endpoint: '',
      remark: ''
    }
  })
  const subscription = reactive({
    project_id: appStore.userStore.project_id,
    urn: '',
    UpdateSubscription: AddSubscription.data
  })
  const eventData = reactive({
    project_id: appStore.userStore.project_id,
    region: appStore.userStore.region,
    offset: 1,
    limit: 10
  })
  const themeList: theme = reactive({
    project_id: appStore.userStore.project_id
  })
  const subscriptions: subscription = reactive({
    project_id: appStore.userStore.project_id,
    urn: ''
  })
  let basicData: { [key: string]: { [key: string]: string } } = reactive({ data: {} })
  let tableTotal = ref(0)
  const getNotification = async () => {
    let res = await eventList.getNotification(eventData)
    if (res.status === 200) {
      basicData.data = res.data
      basicData.data.creation_time = timeFormathmsUTC(basicData.data.creation_time)
      tableData.value = res.data.subcriptions
      tableTotal.value = res.data.subscription_count
    }
  }
  const availableOptions = [
    {
      value: 'NORMAL',
      label: '正常'
    },
    {
      value: 'WARNING',
      label: '警告'
    },
    {
      value: 'INCIDENT',
      label: '事故'
    }
  ]
  const availableOptions1 = [
    {
      value: 'email',
      label: '邮件'
    },
    {
      value: 'sms',
      label: '短信'
    }
  ]
  // 新建
  const assRef = ref<FormInstance>()
  const createInfo = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        try {
          if (information.data.CreateTopic.enterprise_project_id == '') {
            createInformation.enterprise_project_id = '0'
          }
          let res = await eventList.createTopic(createInformation)
          if (res.status < 300) {
            ElMessage({
              message: '创建成功',
              type: 'success'
            })
            getNotification()
            dialogVisible.value = false
          }
        } catch (err) {
          ElMessage.error('创建失败')
        }
      }
    })
  }
  const updata = async () => {
    showRevise.value = true
  }
  const updataSubject = async () => {
    try {
      basicData.data.notice_trace_status = subjectDatas.notice_trace_status
      let res = await eventList.updataTheme(subjectDatas)
      if (res.status < 300) {
        ElMessage({
          message: '修改成功',
          type: 'success'
        })
        getNotification()
        showRevise.value = false
      }
    } catch (err) {
      ElMessage({
        message: '修改失败',
        type: 'error'
      })
    }
  }

  const deleteAs = (name: string) => {
    ElMessageBox.confirm(`确认删除此条数据？\n主题名称: ${name}  `, '警告', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        let res = await eventList.deletemessage(themeList)
        if (res.status === 204) {
          ElMessage({
            message: '删除成功！',
            type: 'success'
          })
          getNotification()
        }
      })
      .catch(() => {})
  }
  const unsubscribe = (urn: any) => {
    ElMessageBox.confirm(`确认取消订阅？`, '提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'info'
    })
      .then(async () => {
        subscriptions.urn = urn
        let res = await eventList.deletesubscribe(subscriptions)
        if (res.status === 202) {
          ElMessage({
            message: '取消订阅成功！',
            type: 'success'
          })
          getNotification()
        }
      })
      .catch(() => {})
  }
  const createSubscription = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        subscription.urn = basicData.data.topic_urn
        try {
          let res = await eventList.addSubscription(subscription)
          if (res.status < 300) {
            ElMessage({
              message: '添加成功',
              type: 'success'
            })
            getNotification()
            showAndhide.value = false
          }
        } catch (err) {
          ElMessage.error('添加失败')
        }
      }
    })
  }
  const small = ref(false)
  const disabled = ref(false)
  const background = ref(true)
  const handleSizeChange = (val: number) => {
    eventData.limit = val
    eventData.offset = 1
    getNotification()
  }
  const handleCurrentChange = (val: number) => {
    eventData.offset = val
    getNotification()
  }
  const dialogVisible = ref(false)
  const showAndhide = ref(false)
  const showRevise = ref(false)

  const dialogVisibtn = async () => {
    dialogVisible.value = true
  }
  const addSubscription = async () => {
    showAndhide.value = true
  }
  getNotification()
</script>
<style lang="scss" scoped>
  #information-box {
    margin-top: 60px;
    color: $text-color;
    .el-dialog .el-form-item {
      flex-direction: column;
      align-items: flex-start;
    }
    .dialog-footer button:first-child {
      margin-right: 10px;
    }
    .dialog-enter-active {
      transition: all 0.3s ease;
    }
    :deep(.el-input__wrapper) {
      width: 480px;
    }
    .el-icon {
      margin-left: 10px;
      color: #b4b6be;
    }
    :deep(.el-form-item__label) {
      display: inline-flex;
      align-items: center;
      color: #333333;
      font-size: 14px;
      font-family: Microsoft YaHei, Microsoft YaHei-Normal;
    }
    .run-box {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 60px;
      width: calc(100% - 200px);
      position: absolute;
      top: 50px;
      left: 200px;
      background-color: $blank-color;
      z-index: 10;

      .state-box {
        display: flex;
        align-items: center;
        margin-left: 20px;

        .run-label {
          font-size: 16px;
          font-weight: bold;
          margin-right: 16px;
        }
        .el-select {
          width: 100px;
        }
        .fleet {
          width: 160px;
          margin-left: 10px;
        }
      }
    }
    .basic-info {
      background-color: $blank-color;
      border: 1px solid $border-color;
      padding: 30px;
      .basic-detail {
        display: flex;
        justify-content: space-between;
        .basic-btn {
          display: flex;
        }
        .btn {
          width: 100px;
          height: 30px;
          margin-left: 20px;
        }
      }
      .basic-title {
        font-size: 14px;
        font-weight: bold;
      }
      .basic-box {
        display: flex;
        flex-wrap: wrap;
        font-size: 14px;
        margin-top: 30px;
        margin-bottom: -10px;
      }
      .content-box {
        width: 33.3%;
        display: flex;
        margin-bottom: 30px;
        .in-box {
          display: flex;
          align-items: center;
          min-height: 14px;
          line-height: 14px;
          :deep(.edit) {
            margin-left: 20px;
          }
          .modify {
            width: 100px;
            margin-left: 20px;
            font-size: 14px;
            color: #325cb0;
            cursor: pointer;
          }
        }
        .content-label {
          width: 130px;
          margin-right: 30px;
          color: $action-color;
        }
        .content-text {
          color: $text-color;
          word-break: break-all;
          line-height: normal;
        }
      }
    }
    .insert-table {
      margin-top: 20px;
    }
    .insert-info {
      margin-top: 20px;
      padding: 30px;
      background-color: $blank-color;
      border: 1px solid $border-color;
      .insert-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        .insert-title {
          font-size: 14px;
          font-weight: bold;
        }
        .btn {
          width: 100px;
          height: 30px;
        }
      }
    }
    .demo-pagination-block {
      margin-top: 20px;
      position: relative;
      .el-pagination {
        justify-content: flex-end;
      }
      :deep(.el-pagination__total) {
        position: absolute;
        left: 0;
      }
      :deep(.el-pagination__sizes) {
        position: absolute;
        left: 58px;
      }
      :deep(.btn-next) {
        min-width: 28px;
        height: 28px;
        background: $blank-color;
        border: 1px solid $border-color;
        color: $text-color;
      }
      :deep(.btn-next:hover) {
        background: $bac-color;
      }
      :deep(.btn-prev) {
        min-width: 28px;
        height: 28px;
        background: $blank-color;
        border: 1px solid $border-color;
        color: $text-color;
      }
      :deep(.btn-prev:hover) {
        background: $bac-color;
      }
      :deep(.el-pager) {
        li {
          padding: 0;
          min-width: 28px;
        }
        .number,
        .more {
          height: 28px;
          background: $blank-color;
          border: 1px solid $border-color;
          color: $text-color;
        }
        .number:hover,
        .more:hover {
          background: $bac-color;
        }
        .is-active {
          border-color: $main-color;
          color: $main-color;
          background: $bac-color;
          font-weight: normal;
        }
      }
    }
    :deep(.el-table) {
      border-radius: 2px;
      font-size: 14px;
      color: $text-color;
      tr {
        border-color: $border-color;
        height: 78px;
      }
      thead > tr:first-child {
        height: 36px;
      }
      .el-table__cell {
        border-right: none;
      }
      .idescribe {
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
      .actions-delete:hover {
        color: $main-color;
        cursor: pointer;
      }
    }

    :deep(.toDetails) {
      color: $main-color;
      cursor: pointer;
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    :deep(.toDetails:hover) {
      text-decoration: underline;
    }
    :deep(.id-box) {
      width: 100%;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    :deep(.cell) {
      padding: 0 30px 0 20px;
    }
  }
</style>
